using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
//using System.Windows.Forms;
using Microsoft.Win32;
using OneNote = Microsoft.Office.Interop.OneNote;
using System.Runtime.InteropServices;

namespace Webber
{
    public class ONWebExport
    {
        private const string WEBFILES_DIRECTORY = "_onefiles/";     //CONSTANT: working directory in output path
        private const string STYLES_DIRECTORY = "style/";         //CONSTANT: name of directory for associated css and js files
        private System.Collections.ArrayList m_invalidFileChar;

        // Private Member variables
        private XmlNode m_Notebook;                 // current notebook being exported
        private XmlNode[] m_Sections;               // current sections of notebook to be exported
        private string m_OutPath;                   // current output path
        private string m_OutName;                   // current file name to output
        private IExportMonitor m_StatusMonitor;     // current StatusMonitor
        private OneNote.Application m_OnApp;        // handles to OneNOte

        private bool m_bTerminate;                  // terminate export operation
        private bool m_bErrorOccured;               // error in export operation


        public ONWebExport(XmlNode xnNotebook, XmlNode[] pxnSections, string strOutLocation, IExportMonitor statusMonitor)
        {
            m_Notebook = xnNotebook;
            m_Sections = pxnSections;
            
            m_StatusMonitor = statusMonitor;
            m_bTerminate = false;

            //m_OutPath = strOutLocation;
            if (strOutLocation.ToLower().Contains("http://") | strOutLocation.ToLower().Contains("https://"))
            {
                int pos = strOutLocation.LastIndexOf('/');
                m_OutName = strOutLocation.Substring(pos + 1);
                m_OutPath = strOutLocation.Substring(0,pos + 1);
            }
            else
            {
                System.IO.FileInfo fileInfo = new System.IO.FileInfo(strOutLocation);
                m_OutName = fileInfo.Name;
                m_OutPath = fileInfo.Directory.FullName;
            }

            // initialize invalid File Char list
            m_invalidFileChar = new System.Collections.ArrayList();
            foreach (char c in System.IO.Path.GetInvalidFileNameChars())
            {
                m_invalidFileChar.Add(c);
            }
        }

        ~ONWebExport()
        {
            
            m_OnApp = null;
        }

        private void ClearLog()
        {
            m_StatusMonitor.ClearLog();
            m_bErrorOccured = false;
        }

        private void LogInfo(string strMsg)
        {
            m_StatusMonitor.AppendLog(strMsg);
        }

        private void LogError(string strMsg)
        {
            m_StatusMonitor.AppendLog(strMsg);
            m_bErrorOccured = true;
        }

        public bool ErrorOccured()
        {
            return m_bErrorOccured;
        }


        private bool ExportFrameset(string strAbsFileName, string defaultPage)
        {
            bool result = true;

            string strFramesetHtml = "<html>\r\n";
            strFramesetHtml += "\t<head><title> Notebook Frameset </title></head>\r\n";
            strFramesetHtml += "\t<frameset cols=\"80%,20%\" framespacing=\"4\" frameborder=\"yes\">\r\n";
            strFramesetHtml += "\t\t<frame name=\"page\" src=\"" + defaultPage + "\" frameborder=\"0\" style=\"border: 1 #4674B9 solid\">\r\n";
            strFramesetHtml += "\t\t<frame name=\"section\" src=\"SectionIndex.htm\" frameborder=\"0\">\r\n";
            strFramesetHtml += "\t\t<noframes>\r\n";
	        strFramesetHtml += "\t\t<body>\r\n";
            strFramesetHtml += "\t\t<p>This page uses frames, but your browser doesn&#39;t support them.</p>\r\n";
            strFramesetHtml += "\t\t</body>\r\n";
            strFramesetHtml += "\t\t</noframes>\r\n";
            strFramesetHtml += "\t</frameset>\r\n";
            strFramesetHtml += "</html>\r\n";

            string error;
            if (!IOHelper.WriteFile(strAbsFileName, strFramesetHtml, false, out error))
            {
                result = false;
                LogError("Failed to export frameset at " + strAbsFileName + ": " + error);
            }

            return result;
        }

        private int GetPageCount()
        {
            int numPages = 0;
            XmlNodeList list;
            foreach (XmlNode node in m_Sections)
            {
                list = ONXmlRequestor.GetNodes(m_OnApp, node.Attributes["ID"].Value, OneNote.HierarchyScope.hsPages, "//one:Page");
                numPages += list.Count;
            }
            return numPages;
        }

        private string GetPageHeader()
        {
            // 8/2/06 - dtse: XHTML makes formatting go wonky...
            //return
                //"<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\r\n" +
                //"<html xmlns=\"http://www.w3.org/1999/xhtml\" style=\"height:100%;width:100%\">\r\n";

            return
                "<html style=\"height:100%;width:100%\">\r\n";
        }
        
        public bool ExportNotebook()
        {
            string error;   // general var to collect error feedback

            // initialize result
            bool result = true;

            // start export log
            ClearLog();
            LogInfo("Exporting Notebook...");

            // trying to get instance of OneNOte
            try
            {
                //System.Windows.Forms.MessageBox.Show("Created Ref");
                m_OnApp = new OneNote.Application();
            }
            catch (Exception e)
            {
                m_OnApp = null;
                result = false;
                LogError(e.Message);
            }

            // Set status dialog range (we double pages to accomodate creation and copying, then add the standard 115 files to get notebook going)
            m_StatusMonitor.SetRange(0, GetPageCount() * 2 + 115);
            
            // Swap real output path with a temporary path
            string destination = m_OutPath;
            m_OutPath = IOHelper.MakeTempDirectory();
            if (m_OutPath == "")
            {
                result = false;
                LogError("Failed to create temp directory for export");
            }
            else
            {
                LogInfo("Creating temporary files at: " + m_OutPath);
            }

            // create output path
            string strCurrentOutPath = m_OutPath + WEBFILES_DIRECTORY;
            if (result)
            {
                if (!IOHelper.CreateDirectory(strCurrentOutPath, out error))
                {
                    result = false;
                    LogError("Failed to create webfiles directory for notebook: " + error);
                }
            }

            // Setup notebook export
            if (result)
            {
                
                // get notebook information
                string strNotebookName;     // name of notebook
                string strNotebookHtml;     // html representation of notebook
                strNotebookName = m_Notebook.Attributes["name"].Value;
                                
                // begin writing notebook file
                strNotebookHtml = GetPageHeader();
                strNotebookHtml += "<head>\r\n";
                strNotebookHtml += "\t<title>" + strNotebookName + "</title>\r\n";

                // write links to supporting css and javascript files
                // 8/2/06 - dtse: embedding the CSS...
                //strNotebookHtml += "\t<link rel=\"stylesheet\" type=\"text/css\" href=\"./" + WEBFILES_DIRECTORY + STYLES_DIRECTORY + "webber.css\"/>\r\n";
                strNotebookHtml += "\t<script type=\"text/javascript\" src=\"./" + WEBFILES_DIRECTORY + STYLES_DIRECTORY + "webber.js\"></script>\r\n";
                strNotebookHtml += "</head>\r\n";

                // setup string for what goes into the body
                strNotebookHtml +=                    
                    "<body style=\"padding:0px; margin:0%; overflow:hidden; background-color:#A9C9F4; margin-top:80px\">\r\n";

                // this is the header part
                strNotebookHtml +=
                    "<div style=\"position:absolute;top:0px; height:80px;width:100%;overflow:hidden\">\r\n" +
                    "   <img style=\"float:left; position:relative; left:10px\" src=\"./_onefiles/style/Title.png\">\r\n" +
                    "   <div style=\"height:20px; float:right; position:absolute; top:5px; right:10px; font: x-small Tahoma;color: #000000;text-decoration: none;white-space: nowrap\">Last Refresh: " + System.DateTime.Now.ToString() + "</div>\r\n" +
                    "   <div style=\"height:25px; float:right; position:absolute; top:25px;right:10px; overflow:hidden\">\r\n" +
                    "       <div style=\"float:left;width:13px;height:25px;background-image:url('./_onefiles/style/Toolbar_left.png')\"></div>\r\n" +
                    "       <div id=\"editbutton\" style=\"float:left;width:128px;height:25px;background-image:url('./_onefiles/style/Toolbar_edit_off.png')\">\r\n" +
                    "           <a  id=\"editbuttonlink\"\r\n"+
                    "               style=\"display:block;width:100%;height:100%\"\r\n" +
                    "               title=\"Edit this page in Microsoft Office OneNote 2007\"\r\n" +
                    "               onmouseover=\"setBackground('editbutton','./_onefiles/style/Toolbar_edit_on.png')\"\r\n" +
                    "               onmouseout=\"setBackground('editbutton','./_onefiles/style/Toolbar_edit_off.png')\">\r\n" +
                    "           </a>\r\n" +
                    "		</div>\r\n" +
                    "       <div style=\"float:left;width:34px;height:25px;background-image:url('./_onefiles/style/Toolbar_divider.png')\"></div>\r\n" +
                    "       <div id=\"leftbutton\" style=\"float:left;width:25px;height:25px;background-image:url('./_onefiles/style/Toolbar_arrowl_off.png')\">\r\n" +
                    "           <a  style=\"display:block;width:100%;height:100%\" href=\"#\" onclick=\"moveSectionTabsRight()\"\r\n" +
                    "               title=\"Scroll Section Tabs Left\"\r\n" +
                    "               onmouseover=\"setBackground('leftbutton','./_onefiles/style/Toolbar_arrowl_on.png')\"\r\n" +
                    "               onmouseout=\"setBackground('leftbutton','./_onefiles/style/Toolbar_arrowl_off.png')\">\r\n" +
                    "		    </a>\r\n" +
                    "		</div>\r\n" +
                    "		<div id=\"rightbutton\" style=\"float:left;width:25px;height:25px;background-image:url('./_onefiles/style/Toolbar_arrowr_off.png')\">\r\n" +
                    "           <a  style=\"display:block;width:100%;height:100%\" href=\"#\" onclick=\"moveSectionTabsLeft()\"\r\n" +
                    "               title=\"Scroll Section Tabs Right\"\r\n" +
                    "               onmouseover=\"setBackground('rightbutton','./_onefiles/style/Toolbar_arrowr_on.png')\"\r\n" +
                    "               onmouseout=\"setBackground('rightbutton','./_onefiles/style/Toolbar_arrowr_off.png')\">\r\n" +
                    "           </a>\r\n" +
                    "       </div>\r\n" +
                    "       <div style=\"float:left;width:29px;height:25px;background-image:url('./_onefiles/style/Toolbar_right.png')\"></div>\r\n" +
                    "   </div>\r\n" +
                    "</div>\r\n";

                // middle part that contains the tabs and content
                strNotebookHtml +=
                    "<div style=\"width:100%;height:98%;\" align=\"center\">\r\n" +
                    "<div style=\"width:99%;height:100%\">\r\n" +
                    "<table style=\"width:100%;height:100%;border-collapse:collapse;margin:0px;padding:0px\">\r\n";

                // first table row that contains the page tabs
                strNotebookHtml +=
                        "\t<tr style=\";margin:0px;padding:0px\">\r\n" +
                        "\t<td style=\"margin:0px;padding:0px;height:20px\">\r\n" +
                        "\t<div id=\"tabs\" style=\"position:absolute;left:5px;height:100%;overflow:hidden;margin:0px;padding:0px;overflow:hidden;z-index:1\">\r\n";

                // first tab elemet that is just padding
                strNotebookHtml +=
                            "\t\t<div id=\"lTabSpace\" style=\"float:left;height:100%;width:20px;border-bottom: 1px #4674B9 solid;\"></div>\r\n";

                // start aggregating sections into html body
                string strSectionURL;      // URL to Page representing Section
                string strFolderName;      // Name of folder to hold Section
                string strFirstURL = "";   // URL to page of the FIRST successfully exported section
                for (int i = 0; i < m_Sections.Length && !m_bTerminate; i++)
                {
                    // Collect relevant information about the tab
                    string strTabId = "tab" + i.ToString();
                    string strSectionName = m_Sections[i].Attributes["name"].Value;
                    string strColor = m_Sections[i].Attributes["color"].Value;

                    // this is for safety in case color returns a blank value
                    if (strColor == "")
                    {
                        strColor = "Blue";
                    }

                    string strSectionPageColor = ONColorMap.GetPageHexColor(strColor);
                    string strSectionColorName = ONColorMap.GetColorName(strColor);


                    // Set Section Folder name
                    
                    // dtse - removing section folder names to accomodate different langauges
                    // strFolderName = GetValidSectionName(strCurrentOutPath, strSectionName);
                    if (/*strFolderName == ""*/ true)
                    {
                        strFolderName = i.ToString() + "/";
                    }

                    // write section tab to HTML
                    strNotebookHtml +=
                            "\t\t<div id=\"" + strTabId + "\" style=\"height:20px;float:left; border-bottom: 1px #4674B9 solid;\">\r\n";
                    
                    // left part of the tab
                    strNotebookHtml +=
                                "\t\t\t<div id=\"" + strTabId + "left\" style=\"height:100%;width:8px;float:left; background-repeat:no-repeat; background-image:url('./" + WEBFILES_DIRECTORY + STYLES_DIRECTORY + strSectionColorName + "Tab_LeftCorner.gif')\"></div>\r\n";

                    // BEGIN: middle part of the tab
                    strNotebookHtml +=
                                "\t\t\t<div id=\"" + strTabId + "mid\" style=\"height:100%;max-width:200px; float:left; background-repeat: repeat-x; white-space: nowrap; overflow: hidden; background-image:url('./" + WEBFILES_DIRECTORY + STYLES_DIRECTORY + strSectionColorName + "Tab_Middle.gif')\">\r\n";

                    // export Section
                    strSectionURL = ExportSection(strCurrentOutPath, strFolderName, m_Sections[i]);
                  
                    if (strSectionURL != "")
                    {
                        strNotebookHtml +=  
                            "\t\t\t\t<a\r\n" +
                            "\t\t\t\t   style=\"font: x-small Tahoma;color: #000000;text-decoration: none;white-space: nowrap\"\r\n" +
                            "\t\t\t\t   href=\"./" + WEBFILES_DIRECTORY + strSectionURL + "\"\r\n" +
                            "\t\t\t\t   target=\"section\"\r\n" +
                            "\t\t\t\t   onclick=\"onClickSectionTab('" + strTabId + "','" + strSectionPageColor + "','" + strSectionColorName + "')\"\r\n" +
                            "\t\t\t\t   onmouseover=\"ColorSectionTab('" + strTabId + "','Rollover')\"\r\n" +
                            "\t\t\t\t   onmouseout=\"ColorSectionTab('" + strTabId + "','" + strSectionColorName + "')\">\r\n" +
                                "\t\t\t\t\t" + strSectionName + "\r\n" +
                            "\t\t\t\t</a>\r\n";

                        // set the first section url if it isn't set already
                        if (strFirstURL.Equals(""))
                        {
                            // set the section that we will default to when notebook is loaded
                            strFirstURL = "./" + WEBFILES_DIRECTORY + strSectionURL;

                            // insert the onload action in the body tag so that the default section appears properly
                            int pos = strNotebookHtml.IndexOf("<body", StringComparison.OrdinalIgnoreCase);
                            if (pos != -1)
                            {
                                strNotebookHtml = strNotebookHtml.Insert(pos + 5," onload=\"onClickSectionTab('" + strTabId + "','" + strSectionPageColor + "','" + strSectionColorName + "')\"");
                            }
                        }
                    }
                    else
                    {
                        strNotebookHtml += "\t\t\t\t<a> \r\n";
                        strNotebookHtml += "\t\t\t\t\t" + strSectionName + "\r\n";
                        strNotebookHtml += "\t\t\t\t</a>\r\n";
                    }
                    
                    // END: middle part of the tab
                    strNotebookHtml += "\t\t\t</div>\r\n";

                    // last part of the tab
                    strNotebookHtml +=
                            "\t\t\t<div id=\"" + strTabId + "right\" style=\"height:100%;width:22px;float:left; background-repeat:no-repeat;background-image:url('./" + WEBFILES_DIRECTORY + STYLES_DIRECTORY + strSectionColorName + "Tab_RightCorner.gif')\"></div>\r\n";
                    
                    // close the whoe tab the tab
                    strNotebookHtml +=
                        "\t\t</div>\r\n";
                }

                // fill in the remaining space of the tab row
                strNotebookHtml +=
                        "\t\t<div style=\"float:none;height:100%;border-bottom: 1px #4674B9 solid;\"></div>\r\n";

                // close up row for section tabs
                strNotebookHtml +=
                    "\t</div>\r\n" +
                    "\t</td>\r\n" +
                    "\t</tr>\r\n";                 

                // add lower chunk 
                strNotebookHtml +=
                    "\t<tr>\r\n" +
                    "\t<td id=\"content\" style=\"padding-top:4px; padding-bottom:4px; padding-left:7px; border-bottom: 1px #4674B9 solid;border-left: 1px #4674B9 solid;border-right: 1px #4674B9 solid;background-position:center; background-repeat:repeat-x\" align=\"center\">\r\n" +
                        "\t\t<iframe style=\"width:100%;height:100%;\" src=\"" + strFirstURL + "\" id=\"frame\" name=\"section\" frameborder=\"0\"> </iframe>\r\n" +
                    "\t</td>\r\n" +
                    "\t</tr>\r\n";

                // close out the document
                strNotebookHtml +=
                    "</table>\r\n" +
                    "</div>\r\n" +
                    "</div>\r\n";

                // add some padding at the bottom
                strNotebookHtml +=
                    "<div style=\"width:100%;height:2%;\"></div>\r\n";

                // close out the document
                strNotebookHtml +=
                    "</body>\r\n" +
                    "</html>\r\n";

                if (m_bTerminate)
                {
                    LogInfo("Notebook Export aborted...");
                    result = false;
                }
                else
                {

                    // Write Notebook HTML to file and copy associated styles
                    // string strNotebookFileName = m_OutPath + "\\" + "WebView.htm";
                    string strNotebookFileName = m_OutPath + "\\" + m_OutName;
                    if (!IOHelper.WriteFile(strNotebookFileName, strNotebookHtml, false, out error))
                    {
                        result = false;
                        LogError("Failed to write Notebook file: " + error);
                    }

                    // copy necessary styles files
                    if (result)
                    {
                        // define location of style files
                        string strStyleDirectory = (string)Registry.GetValue("HKEY_CURRENT_USER\\Software\\David Tse\\OneNote Webber", "AppPath", "");
                        strStyleDirectory += STYLES_DIRECTORY;

                        // copy associated styles
                        if (!IOHelper.CopyDirectory(strStyleDirectory, strCurrentOutPath + "style\\", out error, null))
                        {
                            result = false;
                            LogError("Failed to copy associated styles: " + error);
                        }
                    }
                }
            }

            // if the whole operation succeeded copy file to destination
            if (result)
            {
                // set Status MOnitor to done if publishing succeeds
                result = PublishFilesToDestination(m_OutPath, destination);
                if (result)
                {
                    m_StatusMonitor.SetDone(true);
                }
            }

            // cleanup temp directory
            LogInfo("Removing temporary files");
            if (IOHelper.DeleteDirectory(m_OutPath, out error))
            {
                LogInfo("...Done");
            }
            else
            {
                LogError("Error removing temporary files:" + error);
                // failing to remove temp files doesn't mean export failed
            }

            // release our reference
            m_OnApp = null;

            return result;
        }

        private string EscapeChar(char c, string arg)
        {
            string temp = "";
            for (int i = 0; i < arg.Length; i++)
            {
                if (arg[i] == c)
                {
                    temp += "\\" + c.ToString();
                }
                else
                {
                    temp += arg[i];
                }
            }
            return temp;
        }

        // Exports a section
        // strOutPath - specifies the root folder of the notebook export
        // strFolder - specifies the folder to store section files
        // xnSecNode - XML node that represents section to be exported
        // returns: URL (relative to root folder) to section index page
        private string ExportSection(string strOutPath, string strFolder, XmlNode xnSecNode)
        {
            string error;

            XmlNodeList xnlPageList;    // XML list of pages for section
 
            string strSectionOutPath = "";   // location on disk to store section
            string strSectionURL = "";       // relative path link to section
            string strDefaultEditURL;       // default edit url link when section is loaded
            string strDefaultPageID = "";        // id of page that corresponds with default edit URL

            // get section data
            string sectionId = xnSecNode.Attributes["ID"].Value;        // Section ID
            string sectionName = xnSecNode.Attributes["name"].Value;    // Section Name

            // Section Color Name - default to blue if we have an unrecognized color
            string sectionColorName = ONColorMap.GetColorName(xnSecNode.Attributes["color"].Value);
            if (sectionColorName == "") sectionColorName = "Blue";
            
            // Page color value - default to blue if we have an unrecongized color
            string sectionPageColor = ONColorMap.GetPageHexColor(xnSecNode.Attributes["color"].Value);
            if (sectionPageColor == "") sectionPageColor = "#C4D3F1";

            // get the edit url to the section
            try
            {
                m_OnApp.GetHyperlinkToObject(sectionId, "", out strDefaultEditURL);
                strDefaultEditURL = EscapeChar('\\', strDefaultEditURL); // in case the url contains \ (eg. stored on local file system)
                strDefaultEditURL = EscapeChar('\'', strDefaultEditURL); // in case the url contains ' (eg. if page title is "OneNote's")
            }
            catch (Exception e)
            {
                LogError("Failed to get hyperlink to section: " + e.Message);
                strDefaultEditURL = "";
            }

            // Log
            LogInfo("Exporting section: " + sectionName);

            // Create section directory
            strSectionOutPath = strOutPath + strFolder;
                      
            // Export section if we succeesfully created the directory
            if (!IOHelper.CreateDirectory(strSectionOutPath, out error))
            {
                LogError("Failed to created directory for section: " + error);
            }
            else
            {
                string strSectionHtml;      // html representation of section
                string firstPageURL = "";        // URL to first exported page

                // Write the header part
                strSectionHtml = GetPageHeader();
                strSectionHtml += "<head>\r\n";
                strSectionHtml += "\t<title>" + sectionName + "</title>\r\n";
                
                // 8/2/06 - dtse: no more external css
                // strSectionHtml += "\t<link rel=\"stylesheet\" type=\"text/css\" href=\"../" + STYLES_DIRECTORY + "webber.css\"></link>\r\n";
                
                strSectionHtml += "\t<script type=\"text/javascript\" src=\"../" + STYLES_DIRECTORY + "webber.js\"></script>\r\n";
                strSectionHtml += "</head>\r\n";

                 // Set body color
                strSectionHtml += "<body style=\"margin:0px;padding:0px;width:100%;height:100%;background-position:center; background-repeat:repeat-x; background-image:url('../" + STYLES_DIRECTORY + sectionColorName + "_SectionBG.png'); background-color:" + sectionPageColor + "\">";
             
                // spacer before the page tabs start
                strSectionHtml += "<div style=\"height:20px\"></div>\r\n";
              

                // get pages of section
                xnlPageList = ONXmlRequestor.GetNodes(m_OnApp,sectionId, OneNote.HierarchyScope.hsPages, "//one:Page");

                // if we can get pages, export each page of the section
                if (xnlPageList != null)
                {
                    // Write each page
                    bool result;

                    XmlNode xnPage;
                    for (int i = 0; i < xnlPageList.Count && !m_bTerminate; i++)
                    {
                        // set page name
                        xnPage = xnlPageList.Item(i);

                        // dtse - removing meaningful page names
                        //      - Sharepoint DOesn't like long file names
                        //      - We stumble on foreign languages
                        // set page name
                        //strFileName = GetValidMHTPageName(strSectionOutPath, xnPage.Attributes["name"].Value);
                        //if (strFileName == "")
                        //{
                        //    strFileName = i.ToString() + ".mht";
                        //}

                        string strPageId = "page" + i.ToString();
                        string strFileName = strPageId + ".mht";
                        string strPageGuid = xnPage.Attributes["ID"].Value;
                        string strPageEditUrl;
                        try
                        {
                            m_OnApp.GetHyperlinkToObject(strPageGuid, "", out strPageEditUrl);
                            strPageEditUrl = EscapeChar('\\', strPageEditUrl);
                            strPageEditUrl = EscapeChar('\'', strPageEditUrl); // in case the url contains '
                        }
                        catch (Exception e)
                        {
                            LogError("Failed to get hyperlink to page: " + e.Message);
                            strPageEditUrl = "";
                        }

                     
                        result = ExportPage(strSectionOutPath + strFileName, xnPage);

                        strSectionHtml +=
                            "<div id=\"" + strPageId + "\" style=\"height:23px;width:100%;margin-right:13px\">\r\n" +
	                        "   <div id=\"" + strPageId + "body\" style=\"padding-left:5px;position:absolute;left:0px; width:100%; white-space: nowrap;overflow:hidden;height:23px;float:none;background-image:url('../" + STYLES_DIRECTORY + sectionColorName + "Page_Body.gif');background-position:right;background-repeat:repeat-x\">" +
                            "       <a  style=\"position:relative; top:2px; display:block;width:100%; font-family: Tahoma; font-size: x-small; text-decoration: none; color: #000000; white-space: nowrap\"\r\n" +
			                "           onmouseover=\"onMouseOverPageTab('" + strPageId + "','Rollover')\"\r\n" +
		                    "           onmouseout=\"onMouseExitPageTab('" + strPageId + "','" + sectionColorName + "')\"\r\n" +
                            "		    onclick=\"onClickPageTab('" + strPageId + "','" + sectionColorName + "','" + strPageEditUrl + "')\"\r\n";

                        if (result)
                        {
                            strSectionHtml +=
                            "           href=\"./" + strFileName + "\" target=\"page\">\r\n";

                            if (firstPageURL.Equals(""))
                            {
                                firstPageURL = "./" + strFileName;
                                strDefaultEditURL = strPageEditUrl;
                                strDefaultPageID = strPageId;
                            }
                        }
                        else
                        {
                            strSectionHtml +=
                            "           href=\"#\" target=\"page\">\r\n";
                        }                    

                        strSectionHtml +=
                            "           " + xnPage.Attributes["name"].Value + "\r\n" +
                            "       </a>\r\n" +
                            "   </div>\r\n" +
                            "<div style=\" z-index:1; position:absolute; right:0px; height:23px;width:30px;float:right\"><img id=\"" + strPageId + "corner\" style=\"height:23px\" src=\"../" + STYLES_DIRECTORY + sectionColorName + "Page_RightCorner.gif\"></div>\r\n" +
                            "</div>\r\n";                        
                        
                        // Check if we should terminate
                        if (m_StatusMonitor != null)
                        {
                            m_bTerminate = m_StatusMonitor.ShouldStop();
                        }
                    }
                }
                else
                {
                    LogError("Failed to get page list of section");
                }

                if (m_bTerminate)
                {
                    LogInfo("Terminating Export Operation...");
                }
                else
                {

                    // insert the onload action in the body tag so that the default page appears properly
                    int pos = strSectionHtml.IndexOf("<body", StringComparison.OrdinalIgnoreCase);
                    if (pos != -1)
                    {
                        if (strDefaultPageID.Equals(""))
                        {
                            strSectionHtml = strSectionHtml.Insert(pos + 5, " onload=\"setEditUrl('" + strDefaultEditURL + "')\"");
                        }
                        else
                        {
                            strSectionHtml = strSectionHtml.Insert(pos + 5, " onload=\"onClickPageTab('" + strDefaultPageID + "','" + sectionColorName + "','" + strDefaultEditURL + "')\"");
                        }
                    }

                    // Write the end part
                    strSectionHtml += "</body>\r\n";
                    strSectionHtml += "</html>\r\n";

                    // Write Section Part
                    if (!IOHelper.WriteFile(strSectionOutPath + "SectionIndex.htm", strSectionHtml, false, out error))
                    {
                        LogError("Failed to create html file for section: " + error);
                    }
                    else
                    {
                        // Export corresponding frameset
                        if (ExportFrameset(strSectionOutPath + "SectionFrameset.html", firstPageURL))
                        {
                            LogInfo("...Done");

                            // Form URL to section index for notebook
                            strSectionURL = strFolder + "SectionFrameset.html";
                        }
                        else
                        {
                            LogError("...Failed");
                        }
                    }
                }
            }
            return strSectionURL; /*the link to from top section bar*/
        }

        
        // exports a page to mht
        // strAbsFileName - absolute file location target eg. "C:\\temp\\page1.mht"
        // xnPage - xml node reprsenting page
        private bool ExportPage(string strAbsFileName, XmlNode xnPage)
        {
            bool bExportSuccess = true;             // success of page export operation
            
            // get page data
            string strPageName = xnPage.Attributes["name"].Value;
            string strPageID = xnPage.Attributes["ID"].Value;

            // Tell user what we're doing
            m_StatusMonitor.CurrentStatus("Exporting page " + strPageName);
            
            // if we have reference, try to export the page
            if (m_OnApp != null)
            {
                // Write page (WE ASSUME DIRECTORY EXISTS!)
                try
                {
                    m_OnApp.Publish(strPageID, strAbsFileName, OneNote.PublishFormat.pfMHTML, "");
                }
                catch (Exception e)
                {
                    LogError("Failed to export page " + strPageName + " to " + strAbsFileName +": " + e.Message);
                    bExportSuccess = false;
                }
            }

            // Tell user what we're doing
            m_StatusMonitor.CurrentStatus("");

            // Update status abar
            if (m_StatusMonitor != null) m_StatusMonitor.Increment(1);

            return bExportSuccess;
        }

        private void InsertPlaceholder(string strAbsFileName)
        {
            
            string strHtml;
            strHtml = "<HTML>\r\n";
            strHtml += "\t<TITLE> Placeholder page </TITLE>\r\n";
            strHtml += "\t<BODY>\r\n";
            strHtml += "\t\tOneNote error occured while exporting this page";
            strHtml += "\t</BODY>\r\n";
            strHtml += "</HTML>\r\n";

            // Write Section Part
            string error;
            if (IOHelper.WriteFile(strAbsFileName, strHtml, false, out error))
            {
                // Log
                LogInfo("Exported placeholder in place of page to " + strAbsFileName);
            }
            else
            {
                LogError("Failed to insert placeholder at " + strAbsFileName + ": " + error);
            }
        }

        // returns a clean section name that doesn't currently exist
        // if we can't get a valid section name, we return blank
        private string GetValidSectionName(string path, string rawSectionName)
        {
            string SectionName = IOHelper.GetCleanPathName(rawSectionName);

            if (SectionName != "")
            {
                // test if section exists
                int idx = 1;
                string original = SectionName;
                while (System.IO.Directory.Exists(path + SectionName) && idx < 100)
                {
                    idx++;
                    SectionName = original + idx.ToString();
                }

                if (idx == 100)
                {
                    SectionName = "";
                }
                else
                {
                    SectionName += "\\";
                }
            }
            return SectionName;
        }

        /* dtse - no longer necessary, we gave up on meaningful page names due to different string languages
        // calls this to get a valid name for an mht page at given location
        // rawPageName SHOULD NOT have a .mht extension
        private string GetValidMHTPageName(string path, string rawPageName)
        {
            string PageName = IOHelper.GetCleanFileName(rawPageName);

            if (PageName != "")
            {
                // test if section exists
                int idx = 1;
                string original = PageName;
                while (System.IO.File.Exists(path + PageName + ".mht") && idx < 100)
                {
                    idx++;
                    PageName = original + idx.ToString();
                }

                if (idx == 100)
                {
                    PageName = "";
                }
                else
                {
                    PageName += ".mht";
                }
            }
            return PageName;
        }
        */

        private bool PublishFilesToDestination(string src, string des)
        {
            LogInfo("Publishing notebook to: " + des);

            bool result = true;
            string error = "";

            // check for \ at end of src
            src = src.TrimEnd('\\') + '\\';
            
            // do same for destination string for both http and file system
            System.Uri desUri = new System.Uri(des);
            if (desUri.Scheme == "http")
            {
                des = des.TrimEnd('/') + '/';
            }
            else
            {
                des = des.TrimEnd('\\') + '\\';
            }
            string srcWebViewFile = src + m_OutName;
            string desWebViewFile = des + m_OutName;
            string srcStyleDir = src + WEBFILES_DIRECTORY;
            string desStyleDir = des + WEBFILES_DIRECTORY;

            // Handle SharePoint / WebDav Case
            if (desUri.Scheme == "http")
            {
                if (result) result = IOHelper.CopyFileWebDAV(srcWebViewFile, desWebViewFile, out error);
                if (result) result = IOHelper.CopyDirectoryWebDAV(srcStyleDir, desStyleDir, out error, m_StatusMonitor);
            }

            // Handle normal case
            else
            {
                if (result) result = IOHelper.CopyFile(srcWebViewFile, desWebViewFile, out error);
                if (result) result = IOHelper.CopyDirectory(srcStyleDir, desStyleDir, out error, m_StatusMonitor);
            }

            if (result)
            {
                LogInfo("...Done");
            }
            else
            {
                LogError("Error publishing files: " + error);
            };

            return result;
        }
    }
}
